package com.toocms.jinjuhang.ui.mine.bank_card

import android.app.Application
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.BR
import com.toocms.jinjuhang.config.Constants
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.center.BankListData
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.binding.ItemBinding
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.bus.Messenger
import com.toocms.tab.bus.event.SingleLiveEvent

class BankCardListModel(application: Application) : BaseViewModel<BaseModel>(application) {

    val items = ObservableArrayList<BankCardItemModel>()
    val itemBinding =
        ItemBinding.of<BankCardItemModel>(BR.bankCardItemModel, R.layout.item_back_card)

    val stopRefreshSingleLiveEvent = SingleLiveEvent<Unit>()

    val refreshBindingCommand = BindingCommand<BindingAction>(BindingAction {
        refresh()
    })

    val addBankCardClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        startFragment(EditBankCardFgt::class.java)
    })

    init {
        initializeMessenger()
        refresh(true)
    }

    private fun initializeMessenger() {
        Messenger.getDefault().register(this, Constants.MessengerToken.TOKEN_REFRESH_BANK) {
            refresh()
        }
    }

    private fun refresh(isShowLoading: Boolean = false) {
        bankList(isShowLoading)
    }

    private fun bankList(isShowLoading: Boolean) {
        val params = mapOf(Pair("member_id", UserRepository.user.member_id))
        requestData(Urls.Center.BANK_LIST,
            params,
            resultClass = BankListData::class.java,
            isShowLoading = isShowLoading,
            result = {
                it.list?.forEach { item ->
                    items += BankCardItemModel(this, ObservableField(item))
                }
            },
            finish = {
                stopRefreshSingleLiveEvent.call()
            })
    }

}